/*
 * main.c
 *
 *  Created on: Mar 6, 2015
 *      Author: rj
 */

#include "stdio.h"
#include "sys/socket.h"
#include "netinet/in.h"
#include "arpa/inet.h"
#include "stdlib.h"
#include "string.h"

#define MAXBUF	1024

int main(int argc, char *argv[])
{
	int pid;
	int server_sockfd, new_sockfd;
	socklen_t client_len;
	struct sockaddr_in server_addr;
	struct sockaddr_in client_addr;
	unsigned int myport, lisnum;
	char buf[MAXBUF+1];
	
	
	if(argv[2]){
		printf("argv[2]..\n");
		myport = atoi(argv[2]);
	}
	else {
		printf("!!!argv[2]..\n");
		myport = 9734;
	}
	if(argv[3])
		lisnum = atoi(argv[3]);
	else
		lisnum = 5;
	if ((server_sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
		perror("socket");
		exit(EXIT_FAILURE);
	}
	// 初始化服务器地址
	bzero(&server_addr, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_port = myport;
	if(argv[1])
		server_addr.sin_addr.s_addr = inet_addr(argv[1]);
	else
		server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");//INADDR_ANY;//


	server_addr.sin_family = AF_INET;
	server_addr.sin_port = 9734;
	server_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
	//socket绑定到地址

	if(bind(server_sockfd, (struct sockaddr *) &server_addr, sizeof(struct sockaddr)) == -1){
		perror("bind");
		exit(EXIT_FAILURE);
	}
	// 监听
	if (listen(server_sockfd,lisnum) == -1){
		perror("listen");
		exit(EXIT_FAILURE);
	}
	printf("wait for connect...\n");
	client_len = sizeof(client_addr);
	//阻塞，等待连接
	new_sockfd = accept(server_sockfd, (struct sockaddr *) &client_addr, &client_len);
	if(new_sockfd == -1){
		perror("accept");
		exit(EXIT_FAILURE);
	} else {
		printf("服务器：got connection from %s:%dport,socket:%d\n",\
					inet_ntoa(client_addr.sin_addr),ntohs(client_addr.sin_port), new_sockfd);
	}
	if(-1 == (pid=fork())) {
		perror("fork");
		exit(EXIT_FAILURE);
	} else if(0 == pid) {	//子进程发送消息
		while (1) {
			bzero(buf, MAXBUF+1);
			//printf("请输入要发送的信息：\n");
			fgets(buf, MAXBUF, stdin);
			if (!strncasecmp(buf, "quit", 4)) {
				printf("you choose to quit.\n");
				exit(0);
				break;
			}
			//发送
			client_len = send(new_sockfd, buf, strlen(buf)-1, 0);
			if (client_len < 0) {
				printf("发送失败！\n");
				break;
			}
		}
	} else {	// 父进程接收信息
		while (1) {
			bzero(buf, MAXBUF+1);
			client_len = recv(new_sockfd, buf, MAXBUF, 0);
			if (client_len > 0) {
				printf("<====：%s,%d字节\n", buf, client_len);
			} else if (client_len < 0) {
				printf("接收信息失败！\n");
				break;
			} else {
				printf("对方退出。\n");
				exit(0);
				break;
			}
		}
	}
	close(new_sockfd);
	close(server_sockfd);
	return 0;
}

